package com.example.login.viewmodel

import androidx.lifecycle.viewModelScope
import com.example.common.vm.BaseViewModel
import com.example.login.intent.LoginViewIntent
import com.example.login.model.LoginRepository
import com.example.login.uistate.LoginUiState
import com.google.gson.Gson
import com.tencent.mmkv.MMKV
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import javax.inject.Inject
/**
 * 登录的VIewModel
 * */

@HiltViewModel
class LoginViewModel @Inject constructor(private val repository: LoginRepository): BaseViewModel<LoginViewIntent>() {

    private val _uiSate = MutableStateFlow<LoginUiState>(LoginUiState.loadEmpty)
    val uiState:StateFlow<LoginUiState> =_uiSate.asStateFlow()

    override fun dispatchIntent(intent: LoginViewIntent) {
        when(intent){
            is LoginViewIntent.loginToServer->loginSimpleData(intent.username,intent.password)
            is LoginViewIntent.registerToServer->registerSimpleData(intent.username,intent.password)
            else->{}
        }
    }

    //登录
    private fun loginSimpleData(username: String, password: String) {
        viewModelScope.launch(Dispatchers.IO) {
            try {//封装参数
                var mapPrams = mutableMapOf("uName" to username,"uPwd" to password)
                mapPrams.put("time",(System.currentTimeMillis()/1000).toString())
                val json = Gson().toJson(mapPrams).toString()
                var body:RequestBody=RequestBody.create("application/json;charset=UTF-8".toMediaTypeOrNull(),json)
                //调用接口返回数据
                var resultData =repository.loginToServer(body)
                if (resultData.statuesCode=="200"){
                    MMKV.defaultMMKV().encode("token",resultData.getValues().token)
                    MMKV.defaultMMKV().encode("main_url",resultData.home)
                    MMKV.defaultMMKV().encode("userId",resultData.getValues().uId)
                    _uiSate.value = LoginUiState.LoginSuccess(resultData.getValues())
                }else{
                    _uiSate.value = LoginUiState.LoginFail(resultData.msg)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }finally {
                cancel()
            }
        }
    }
    //注册
    private fun registerSimpleData(username: String, password: String) {
        viewModelScope.launch(Dispatchers.IO) {
            try {//封装参数
                var mapPrams = mutableMapOf("uName" to username,"uPwd" to password)
                mapPrams.put("time",(System.currentTimeMillis()/1000).toString())
                val json = Gson().toJson(mapPrams).toString()
                var body:RequestBody=RequestBody.create("application/json;charset=UTF-8".toMediaTypeOrNull(),json)
                //调用接口返回数据
                var resultData =repository.registerToServer(body)
                if (resultData.statuesCode=="200"){

                    _uiSate.value = LoginUiState.registerSuccess(resultData.getValues())
                }else{
                    _uiSate.value = LoginUiState.registerFail(resultData.msg)
                }
            } catch (e: Exception) {
               e.printStackTrace()
            } finally {
                cancel()
            }
        }
    }
}